import network
import micropython
import time
from irctrl import IRReceiver, IRSender, IRCmds
from microdot import Microdot, Response, send_file

def init():
    #初始化
    print("初始化...")
    global reciver, sender, cmds
    reciver = IRReceiver(14)
    sender = IRSender(12)
    cmds = IRCmds('cmds.json')
    
#连接到网络
def connect_wifi(ssid, pwd):
    #连接到WiFi网络
    try:
        print('尝试连接到WiFi'+ssid)
        wlan = network.WLAN(network.STA_IF) # 创建站点接口
        wlan.active(False)
        wlan.active(True)                   # 激活接口
        if not wlan.isconnected():          # 检查是否连接 
            wlan.connect(ssid, pwd)    # 连接到热点
            i = 0
            while not wlan.isconnected():   # 检查状态直到连接到热点或失败
                time.sleep(1) #等待1秒
                print('正在连接',ssid,i)
                i = i+1
                if i>=10: #大于10秒超时，返回
                    print('连接WiFi热点%s失败'%(ssid))   
                    return None
        print('已经连接到WiFi%s'%(ssid))        
        print('网络信息:', wlan.ifconfig()) #打印网络信息
        return wlan.ifconfig() #连接成功后返回网络信息
    except Exception as e:
        print(e)
        return None

def learn_cmd(key):
    #执行学习
    if key:
        global reciver, cmds
        reciver.start()
        if reciver.values and len(reciver.values)>5:
            cmds.set_cmd(key, reciver.values)
            return True
    return False
    
def send_cmd(key):
    #执行发送
    if key:
        global sender, cmds
        values = cmds.get_cmd(key)
        print(values)
        if values and len(values)>5:
            sender.send(values)
            return True
    return False


def start_server(ip):
    #启动web服务
    app = Microdot()# 创建Web服务
    @app.route('/')  #绑定缺省页面的路由
    def index_page(request):
        #print('/ 配置页面请求，返回index.html')
        return send_file('index.html')
    
    @app.route('/getkeys', ['POST'])
    def get_keys(request):
        global cmds
        keys = cmds.get_keys()
        return Response(body = {"code":0, "msg":"ok", "keys":keys})
        
    @app.route('/learn', ['POST'])  #学习遥控器按键
    def do_learn(request):
        #学习按键
        data = request.json
        if data:
            key = data.get("key")
            if learn_cmd(key):
                return Response(body = {"code":0, "msg":"ok"})
        return Response(body={"code":-1, "msg":"操作失败"}) #返回操作失败
    
    @app.route('/send', ['POST'])  #发射遥控器按键
    def do_send(request):
        #发送按键
        data = request.json
        if data:
            key = data.get("key")
            if send_cmd(key):
                return Response(body = {"code":0, "msg":"ok"})
        return Response(body={"code":-1, "msg":"操作失败"}) #返回操作失败
    # 打印服务的地址
    print("服务已经启动，请使用浏览器访问： http://%s "%(ip))
    app.run(host='0.0.0.0', port=80)


def main():
    #主函数
    #初始化
    init()
    #连接到WiFi网络
    ipcfg= connect_wifi("WiFi热点","wifi密码")
    if ipcfg:
        #启动Web服务
        start_server(ipcfg[0])
main() #执行主函数